﻿#include "stdafx.h"

#include "Include/configure.h"
#include "string_helper.h"

namespace spbma
{


	Configure & Configure::Instance()
	{
		static Configure instance;
		return instance;
	}

	Configure::Configure() : _configure_file_path("../Configure.configure")
	{
		ifstream f(_configure_file_path.c_str());

		while(f.is_open() && !f.eof())
		{
			string line;
			getline(f, line);
			string_helper::Trim(line);

			if (!line.empty() && line[0] != '#')
			{//非注释行和非空白行
				string::size_type split_pos = line.find('=');
				_configure_items[line.substr(0, split_pos)] = line.substr(split_pos + 1, line.length() - split_pos - 1);
			}
		}
	}

	string Configure::GetConfig(string const &key) const
	{
		map<string, string>::const_iterator citer = _configure_items.find(key);
		if (citer != _configure_items.end())
		{
			return citer->second;
		}
		return "";
	}

	void Configure::SetConfig( string const &key, string const &new_value )
	{
		if (_configure_items.find(key) != _configure_items.end())
		{
			_configure_items[key] = new_value;
			fstream f;

			//先全部读取出来
			f.open(_configure_file_path.c_str(), ios::in);
			vector<string> file_content;
			while (f.is_open() && !f.eof())
			{
				string str;
				getline(f, str);
				file_content.push_back(str);
			}
			f.close();

			//再修改相应的项并写回去
			f.open(_configure_file_path.c_str(), ios::out);
			for (size_t i = 0; i < file_content.size(); ++i)
			{
				string &line = file_content[i];
				string_helper::Trim(line);

				if (!line.empty() && line[0] != '#')
				{//非空白行和注释行
					string line_key = line.substr(0, line.find('='));
					if (line_key == key)
					{
						line = (key + "=" + new_value);
					}
				}

				f << line;
				if (i != file_content.size() - 1)
				{
					f << endl;
				}				
			}

			_configure_items[key] = new_value;
		}
	}

}